<?php

namespace App\Http\Controllers\Api;

use App\Model\AdminLog;
use App\Model\CloseRoomLog;
use App\Model\FinancePearlStream;
use App\Model\FinancePearlWealth;
use App\Model\FinanceWealthStream;
use App\Model\OperationLogs;
use App\Model\Room;
use App\Model\RoomDynamic;
use App\Model\RoomDynamicLog;
use App\Model\RoomOpLog;
use App\Model\RoomReco;
use App\Model\RoomRecommend;
use App\Model\RoomRecommendLabel;
use App\Model\RoomReport;
use App\Model\RoomScore;
use App\Model\RoomShotoff;
use App\Model\RoomTag;
use App\Model\RoomType;
use App\Model\RoomVote;
use App\Model\CbdViolationRecord;
use App\Model\Users;
use App\Model\Union;
use App\Model\RoomRole;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Illuminate\Validation\Rule;
use phpDocumentor\Reflection\Types\Self_;

class RoomController extends BaseController
{
    protected $tagModel;
    protected $model;

    public function __construct(Request $request, Room $room, RoomTag $roomTag)
    {
        parent::__construct($request);
        $this->model = $room;
        $this->tagModel = $roomTag;
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $list = $this->model->getRoomList($request->all());
        $list = json_decode(json_encode($list), 1);

        //房间积分数据
        /*if(count($list['data']) > 0){
            $roomScoreModel = new RoomScore();
            $roomIds = array_column($list['data'],'room_id');
            $roomScoreMap = $roomScoreModel->getReputationByRoomIds($roomIds);
            foreach ($list['data'] as &$d){
                $score = $roomScoreMap[$d['room_id']] ?? 0;
                $d['reputation'] = $roomScoreModel->reputation($score);
            }
        }*/
        return $this->toJson(self::SUCCESS, $list);
    }

    /**
     * 房间认证
     * @param Request $request
     * @param $room_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function setCertified(Request $request, $room_id, RoomOpLog $roomOpLog)
    {
        $validator = Validator::make($request->all(), [
            'certified' => 'bail|required|integer',
            'desc' => 'bail|required|string'

        ], [
            'certified.required' => '房间认证不可为空',
            'desc.required' => '认证描述不可为空'

        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }


        $res = curl_request(getKkaudioApiUrl() . '/inner/room/set_cert', [
            'room_id' => $room_id,
            'val' => $request->input('certified')
        ], 'json', 'POST');
        if ($res['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::ROOM, "设置认证", $room_id);

            $op_log = [
                'user_id' => $this->user->id,
                'room_id' => $room_id,
                'op' => $request->input('certified'),
                'desc' => $request->input('desc')
            ];
            $roomOpLog->createData($op_log);
            return $this->toJson();
        }
        return $this->toJson(self::ERROR, [], $res['msg']);
    }

    private $official_comment_list = [
        0 => '',
        1 => '/room/tags/guanfangtuijian.png'
    ];

    /**
     * 官方推荐
     * @param Request $request
     * @param $room_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function setRoomTag(Request $request, $room_id)
    {
        $data = ['room_id' => $room_id, 'room_tag' => $this->official_comment_list[$request->input('room_tag')]];
        $res = $this->model->updateData($data);
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, $res);
        }
        OperationLogs::createData($request, OperationLogs::ROOM, '官方推荐', $room_id);
        return $this->toJson(self::SUCCESS, $res);
    }

    /**
     * 兑换比例
     * @param Request $request
     * @param $room_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function setRoomRate(Request $request, $room_id)
    {
        $data = $request->except('_url', 'token');
        $data['room_id'] = $room_id;
        $res = $this->model->updateData($data);
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, $res);
        }
        OperationLogs::createData($request, OperationLogs::ROOM, '设置兑换比例', $room_id);
        return $this->toJson(self::SUCCESS, $res);
    }

    /**
     * 推荐系数
     * @param Request $request
     * @param $room_id
     * @return \Illuminate\Http\JsonResponse
     */
    public function setRoomCoefficient(Request $request, $room_id, RoomRecommend $RoomRecommend)
    {
//        $model = RoomRecommend::find($room_id);
//        if (!$model) {
//            $model = new RoomRecommend();
//            $model->create($request->all());
//            return $this->toJson();
//        }
//        $model->coefficient = $request->input('coefficient');
//        $model->save();
        $res = $RoomRecommend->createData($request->except('_url', 'token'));
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, $res);
        }
        OperationLogs::createData($request, OperationLogs::ROOM, '推荐系数', $room_id);
        return $this->toJson();
    }

    public function setRoomImage(Request $request, $room_id)
    {
        $image = $request->input('image');
        if (!$image)
            $image = Room::IMAGE;
        $res = curl_request(getKkaudioApiUrl() . '/inner/room/set_image', [
            'room_id' => $room_id,
            'image' => $image
        ], 'json', 'POST');
        if ($res['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::ROOM, "设置房间图片", $room_id);
            return $this->toJson(self::SUCCESS, config('kkaudio.oss_url') . $image);
        }
        return $this->toJson(self::ERROR, [], $res['msg']);
    }

    public function setRoomName(Request $request, $room_id)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'bail|required|string'
        ], [
            'name.required' => '房间名不可为空'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }

        $res = curl_request(getKkaudioApiUrl() . '/inner/room/set_name', [
            'room_id' => $room_id,
            'name' => $request->input('name')
        ], 'json', 'POST');
        if ($res['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::ROOM, "设置房间名", $room_id);
            return $this->toJson();
        }
        return $this->toJson(self::ERROR, [], $res['msg']);
    }

    public function setRoomDesc(Request $request, $room_id)
    {
        $validator = Validator::make($request->all(), [
            'desc' => 'bail|required|string'
        ], [
            'desc.required' => '房间简介不可为空'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }

        $res = curl_request(getKkaudioApiUrl() . '/inner/room/set_desc', [
            'room_id' => $room_id,
            'desc' => $request->input('desc')
        ], 'json', 'POST');
        if ($res['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::ROOM, "设置房间简介", $room_id);
            return $this->toJson();
        }
        return $this->toJson(self::ERROR, [], $res['msg']);
    }

    public function setRoomNotice(Request $request, $room_id)
    {
        $validator = Validator::make($request->all(), [
            'notice' => 'bail|required|string'
        ], [
            'notice.required' => '房间公告不可为空'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::ERROR, [], $validator->errors()->all()[0]);
        }

        $res = curl_request(getKkaudioApiUrl() . '/inner/room/set_notice', [
            'room_id' => $room_id,
            'notice' => $request->input('notice')
        ], 'json', 'POST');
        if ($res['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::ROOM, "设置房间公告", $room_id);
            return $this->toJson();
        }
        return $this->toJson(self::ERROR, [], $res['msg']);
    }

    public function getRoomType(Request $request)
    {
        return $this->toJson(self::SUCCESS, RoomType::roomTypeList($request->input()));
    }

    public function getRoomTypeList()
    {
        return $this->toJson(self::SUCCESS, RoomType::getRoomTypeList());
    }

    public function getRoomWater(Request $request, FinanceWealthStream $financeWealthStream, $room_id)
    {
        return $this->toJson(self::SUCCESS, $financeWealthStream->getRoomWealthWater($request, $room_id));
    }

    //获取房间魅力榜查询
    public function getRoomCharm(Request $request, FinanceWealthStream $financeWealthStream, $room_id)
    {
        return $this->toJson(self::SUCCESS, $financeWealthStream->getRoomCharm($request, $room_id));
    }
    //获取房间财富个人榜查询
    public function getRoomWealth(Request $request, FinanceWealthStream $financeWealthStream, $room_id)
    {
        return $this->toJson(self::SUCCESS, $financeWealthStream->getRoomWealth($request, $room_id));
    }

    public function getRecommendRoomList(Request $request, RoomReco $roomReco)
    {
        return $this->toJson(self::SUCCESS, $roomReco->getList($request));
    }

    public function getRoomLabel(RoomRecommendLabel $roomRecommendLabel)
    {
        return $this->toJson(self::SUCCESS, $roomRecommendLabel->getList());
    }

    public function deleteRoomLabel($id, RoomRecommendLabel $roomRecommendLabel)
    {
        return $this->toJson(self::SUCCESS, $roomRecommendLabel->delRoomLabel($id));
    }

    public function createRecommendRoom(Request $request, RoomReco $roomReco)
    {
        $validator = Validator::make($request->all(), [
            'room_id' => 'bail|required|exists:api.room',
            'sort' => 'required',
        ], [
            'room_id.required' => '房间不可为空',
            'room_id.exists' => '该房间不存在',
            'sort.required' => '排序不能为空',
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }
        $res = $roomReco->createData($request->only(['room_id', 'label_id', 'sort']));
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, $res);
        }
        OperationLogs::createData($request, OperationLogs::ROOM, '新增房间推荐标签', $request->input('room_id'));
        return $this->toJson(self::SUCCESS, $res);
    }

    public function updateRecommendRoom(Request $request, $id, RoomReco $roomReco)
    {
        $validator = Validator::make($request->all(), [
            'room_id' => 'bail|required|exists:api.room',
            'sort' => 'required',
        ], [
            'room_id.required' => '房间不可为空',
            'room_id.exists' => '该房间不存在',
            'sort.required' => '排序不能为空',
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }
        $res = $roomReco->updateData($request->only(['room_id', 'label_id', 'sort']));
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, $res);
        }
        OperationLogs::createData($request, OperationLogs::ROOM, '编辑房间推荐标签', $request->input('room_id'));
        return $this->toJson(self::SUCCESS, $res);
    }

    public function deleteRecommendRoom(Request $request, $id, RoomReco $roomReco)
    {
        $res = $roomReco->deleteData(['id' => $id]);
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, $res);
        }
        OperationLogs::createData($request, OperationLogs::ROOM, '删除房间推荐', $id);
        return $this->toJson(self::SUCCESS, $res);
    }

    /**
     * 新增标签
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function createRoomLabel(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'name' => 'required',
            'animate_resource' => 'required_if:new_animate_resource,""',
            'new_animate_resource' => 'required_if:animate_resource,""',
        ], [
            'name.required' => '请填写标签名称',
            'animate_resource.required_if' => '请上传 标签图片 或 标签svga',
            'new_animate_resource.required_if' => '请上传 标签图片 或 标签svga',
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        $goods = $this->model->labelCreate($request->all());
        if ($goods['code'] !== 0) {
            return $this->toJson(self::ERROR, $goods);
        }

        $data['label_id'] = $goods['data']['label_id'];
        OperationLogs::createData($request, OperationLogs::GOODS, '新增房间标签');
        return $this->toJson(self::SUCCESS, $data);
    }

    /**
     * 更新标签
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function updateRoomLabel(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'id' => 'required',
            'name' => 'required',
            'animate_resource' => 'required_if:new_animate_resource,""',
            'new_animate_resource' => 'required_if:animate_resource,""',
        ], [
            'id.required' => '缺少参数:标签ID',
            'name.required' => '请填写标签名称',
            'animate_resource.required_if' => '请上传 标签图片 或 标签svga',
            'new_animate_resource.required_if' => '请上传 标签图片 或 标签svga',
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        $goods = $this->model->labelEdit($request->all());
        if ($goods['code'] !== 0) {
            return $this->toJson(self::ERROR);
        }

        return $this->toJson(self::SUCCESS);
    }

    public function getRooms(Request $request)
    {
        return $this->toJson(self::SUCCESS, $this->model->getRoomByRoomUid($request));
    }

    public function getRoomOpLogList($room_id, RoomOpLog $roomOpLog)
    {
        return $this->toJson(self::SUCCESS, $roomOpLog->getList($room_id));
    }


    //设置允许访问房间类型
    public function getRoomAllowType(Request $request)
    {
        $res = curl_request(getKkaudioApiUrl() . '/inner/room/get_room_allow_type', [], 'json', 'POST');

        if ($res['code'] == 0) {
            $typeArr = RoomType::roomTypeList();
            foreach ($res['data'] as &$v) {
                $v['typeStr'] = '';
                $column = array_column($typeArr, null, 'type_id');
                $intersect = array_intersect_key($column, array_flip(explode(',', $v['typeIds'])));
                $type_key = array_column($intersect, 'type_name');
                $v['typeStr'] = implode(',', $type_key);
            }
            unset($v);

            return $this->toJson(self::SUCCESS, $res['data']);
        }
        return $this->toJson(self::ERROR);
    }


    //获取已选择类型
    public function getApiRoomType(Request $request)
    {
        $roomType = RoomType::roomTypeList();
        foreach ($roomType as $v) {
            $type[] = [
                'id' => $v['type_id'],
                'label' => $v['type_name'],
                'children' => []
            ];
        }
        $checkTypeId = [];
        if ($request->post('roomTypeName')) {
            $roomCheckType = RoomType::getRoomTypeInTypeName(explode(',', $request->post('roomTypeName')));
            foreach (json_decode($roomCheckType, true) as $v) {
                $checkTypeId[] = $v['type_id'];
            }
        }
        $data['type'] = $type;
        $data['checkTypeId'] = $checkTypeId;
        return $this->toJson(self::SUCCESS, $data);
    }


    //更新可访问类型
    public function updateRoomAllowType(Request $request)
    {
        $res = $request->post();
        $str = '';
        if (isset($res['roomTypeId'])) {
            $roomType = RoomType::getRoomTypeInIds($res['roomTypeId']);
            foreach (json_decode($roomType, true) as $v) {
                $str .= $v['type_id'] . ',';
            }
        }
        $res = curl_request(getKkaudioApiUrl() . '/inner/room/set_room_allow_type', [
            'type' => $res['typeId'],
            'typeJson' => rtrim($str, ','),
        ], 'json', 'POST');
        if ($res['code'] == 0) {
            return $this->toJson(self::SUCCESS);
        }
        return $this->toJson(self::ERROR);

    }


    /*
     * 获取房间信息
     * */
    public function getRoomInfo(Request $request)
    {
        $room_id = $request->post('room_id');
        $room_uid = $request->post('room_uid');
        $room = new Room();
        $roomInfo = [];
        if ($room_id) {
            $roomInfo = $room->getRoomByRoomid($room_id);
        }
        if ($room_uid) {
            $roomInfo = $room->getRoomByRoomUid($request);
        }
        return $this->toJson(self::SUCCESS, $roomInfo);
    }


    /*
    * 关闭房间  生成关闭记录
    * */
    public function closeRoom(Request $request)
    {
        $admin = json_decode($this->user, true);
        $reason = $request->post();
        $room = new Room();
        $roomInfo = json_decode($room->getRoomByRoomUid($request), true);
        if (!$roomInfo)
            return $this->toJson(self::ROOM_INFO_ERROR);
        //请求成功
        //发送接口请求
        $res = curl_request(getKkaudioApiUrl() . '/inner/room/kill', [
            'room_id' => $roomInfo[0]['room_id']
        ], 'json', 'POST');
        if ($res['code'] !== 0) {
            return $this->toJson(self::CLOSE_ROOM_ERROR);
        }else{
            $roomrole = new RoomRole();
            $update=$roomrole->updateRoomRole($roomInfo[0]['room_id']);

        }
        $data['room_uid'] = $roomInfo[0]['room_uid'];
        $data['room_id'] = $roomInfo[0]['room_id'];
        $data['room_name'] = $roomInfo[0]['name'];
        $data['desc'] = $reason['close_reason'] ?? '暂无理由';
        $data['admin_id'] = $admin['id'];
        $data['admin_name'] = $admin['name'];
        $data['created_at'] = $data['updated_at'] = date('y-m-d H:i:s');
        $log = CloseRoomLog::addLog($data);
        if ($log) {
            return $this->toJson(self::SUCCESS);
        }
        return $this->toJson(self::ERROR);
    }
    /*
     * 开启房间  生成开启记录
     * */
    public function openRoom(Request $request)
    {
        $admin = json_decode($this->user, true);
        $room = new Room();
        $roomInfo = json_decode($room->getRoomByRoomUid($request), true);
        if (!$roomInfo)
            return $this->toJson(self::ROOM_INFO_ERROR);
        //请求成功
        //更新role表房主
        $roomrole = new RoomRole();
        $roomrole->updateRoomRoleType($roomInfo[0]['room_id']);
        //发送接口请求
        $res = curl_request(getKkaudioApiUrl() . '/chamber/open', [
            'room_id' => $roomInfo[0]['room_id'],
            'admin_id' => 18
        ], 'json', 'POST');

        $data['room_uid'] = $roomInfo[0]['room_uid'];
        $data['room_id'] = $roomInfo[0]['room_id'];
        $data['room_name'] = $roomInfo[0]['name'];
        $data['desc'] = '开启房间';
        $data['admin_id'] = $admin['id'];
        $data['admin_name'] = $admin['name'];
        $data['created_at'] = $data['updated_at'] = date('y-m-d H:i:s');
        $log = CloseRoomLog::addLog($data);
        if ($log) {
            return $this->toJson(self::SUCCESS);
        }

        return $this->toJson(self::ERROR);
    }

    /*
     * 获取日志列表
     * */
    public function getCloseRoomLogList(Request $request, CloseRoomLog $closeRoomLog)
    {
        return $this->toJson(self::SUCCESS, $closeRoomLog->getList($request));
    }

    /*
         * 修改关闭理由
         * */
    public function editCloseRoomReason(Request $request)
    {
        $id = $request->post('id');

        if (!$id)
            return $this->toJson(self::PARAM_ERROR);
        $data['desc'] = $request->post('close_reason');
        $room = new CloseRoomLog();
        $res = $room->editLog($id, $data);
        if ($res)
            return $this->toJson(self::SUCCESS);
        return $this->toJson(self::PARAM_ERROR);
    }

    public function delCloseRoomLog(CloseRoomLog $closeRoomLog, Request $request)
    {
        $id = $request->post('id');
        if (!$id)
            return $this->toJson(self::PARAM_ERROR);
        $data['type'] = 0;
        $res = $closeRoomLog->editLog($id, $data);
        if ($res)
            return $this->toJson(self::SUCCESS);
        return $this->toJson(self::PARAM_ERROR);
    }

    public function cabinList(Request $request)
    {
        dd($request->all());
        return $this->toJson(self::SUCCESS, $this->model->getRoomList($request->all()));
    }


    public function getTagList(Request $request)
    {
        $type = $request->input('type') ?? 0;
        return $this->toJson(self::SUCCESS, $this->tagModel->getTagByType($type));
    }

    public function delTag(Request $request)
    {
        $data = $request->all();
        return $this->toJson(self::SUCCESS, $this->tagModel->delTag($data));
    }

    public function getTagInfo(Request $request)
    {
        $id = $request->input('id') ?? 0;
        return $this->toJson(self::SUCCESS, $this->tagModel->getTagById($id));
    }

    public function createTag(Request $request)
    {
        $data = $request->all();
        return $this->toJson(self::SUCCESS, $this->tagModel->createTag($data));
    }
    /**
     * 房间更新靓号 0关闭1显示
     */
    public function liangTag(Request $request)
    {
        $data = $request->all();
        return $this->toJson(self::SUCCESS, $this->tagModel->liangTag($data));
    }

    public function heartStatus(Request $request)
    {
        $data = $request->all();
        return $this->toJson(self::SUCCESS, $this->tagModel->heart($data));
    }

    public function createCBDRoom(Request $request, RoomOpLog $roomOpLog, Union $union)
    {
        $data = $request->all();
        if (isset($data['room_tag'])) {
            $data['room_tag'] = $this->official_comment_list[$data['room_tag']];
        }
        $res = $this->model->createCBDRoom($data);
        if(isset($res['code']) && $res['code']==0) {
            OperationLogs::createData($request, OperationLogs::ROOM, '创建CBD房间');

            $roomId = $res['data']['room_id'];
            //认证
            if(!empty($data['ifCertified'])) {
                $res2 = curl_request(getKkaudioApiUrl() . '/inner/room/set_cert', ['room_id' => $roomId,'val' => 1], 'json', 'POST');
                if (isset($res2['code']) && $res2['code'] == 0) {
                    OperationLogs::createData($request, OperationLogs::ROOM, "设置认证", $roomId);

                    $op_log = [
                        'user_id' => $this->user->id,
                        'room_id' => $roomId,
                        'op' => 1,
                        'desc' => '创建CBD房间同时认证'
                    ];
                    $roomOpLog->createData($op_log);
                }else{
                    return $this->toJson(self::ERROR, [], '创建CBD房间成功 认证失败');    
                }
            }

            //是否编入公会
            if(!empty($data['ifUnion'])) {
                //获取房主公会ID
                $unionInfo = $union->getUnionInfo($data['user_id']);
                if(empty($unionInfo)) {
                    return $this->toJson(self::ERROR, [], '创建CBD房间成功 编入公会失败:用户无公会');    
                }
                $res3 = json_decode(curlRequest(getKkaudioApiUrl() . '/inner/union/roomJoinUnion', ['union_id'=>$unionInfo['id'],'room_id'=>$roomId]), true);
                if (isset($res3['code']) && $res3['code'] == 0) {
                    OperationLogs::createData($request, OperationLogs::UNION, '房间编入公会');
                }else{
                    return $this->toJson(self::ERROR, [], '创建CBD房间成功 编入公会失败');    
                }
            }
        }else{
            return $this->toJson(self::ERROR, [], empty($res['msg'])?'异常':$res['msg']); 
        }

        return $this->toJson(self::SUCCESS, $res);
    }
    /**
     * 编辑CBD房间信息
     */
    public function updateCBDRoom(Request $request)
    {
        $data = $request->all();
        $data['room_tag'] = isset($data['room_tag']) ? $this->official_comment_list[$data['room_tag']] : '';
        $res = $this->model->updateCBDRoom($data);
        if(isset($res['code']) && $res['code']==0) {
            OperationLogs::createData($request, OperationLogs::ROOM, '更新CBD房间');
        }else{
            return $this->toJson(self::ERROR, [], empty($res['msg'])?'异常':$res['msg']); 
        }
        return $this->toJson(self::SUCCESS, $res);
    }

    public function updateCbdUid(Request $request)
    {
        $data = $request->all();
        //校验重复问题
        $roomId = $request->input('room_id');
        $roomUid = $request->input('room_uid');
        if(!empty($roomId) && !empty($roomUid)) {
            $list = $this->model->getRoomInfo([$roomUid]);
            if(!empty($list)) {
                if($list[0]['room_id'] != $roomId) {
                    return $this->toJson(self::ERROR, [], '房间uid已存在不可设置');    
                }
            }
        }

        $res = $this->model->updateData($data);
        if(isset($res['code']) && $res['code']==0) {
            OperationLogs::createData($request, OperationLogs::ROOM, 'updateCbdUid');
            return $this->toJson(self::SUCCESS, $res);
        }
        return $this->toJson($res['code'] ?? self::ERROR, [], $res['msg'] ?? '失败');

    }

    public function getCabinWater(Request $request, FinancePearlStream $financePearlWealth, $room_id)
    {
        return $this->toJson(self::SUCCESS, $financePearlWealth->getCabinWealthWater($request, $room_id));
    }

    public function setMeleeState(Request $request, $room_id, Room $room)
    {
        $state = $request->input('state');
        return $this->toJson(self::SUCCESS, $room->setMeleeState($room_id, $state));
    }

    public function setTallyState(Request $request, $room_id, Room $room)
    {
        $state = $request->input('state');
        return $this->toJson(self::SUCCESS, $room->setTallyState($room_id, $state));
    }

    public function setDialState(Request $request, $room_id, Room $room)
    {
        $state = $request->input('state');
        return $this->toJson(self::SUCCESS, $room->setDialState($room_id, $state));
    }

    public function setPkState(Request $request, $room_id, Room $room)
    {
        $state = $request->input('state');
        return $this->toJson(self::SUCCESS, $room->setPkState($room_id, $state));
    }

    public function setSpanPkState(Request $request, $room_id, Room $room)
    {
        $state = $request->input('state');
        return $this->toJson(self::SUCCESS, $room->setSpanPkState($room_id, $state));
    }

    public function getRoomCateType(Request $request, Room $room)
    {
        return $this->toJson(self::SUCCESS, $room->getRoomCateType());

    }

    public function setCabinType(Request $request)
    {
        $input = $request->input();
        $check_title = strstr($input['title'], '，');
        if ($check_title) {
            return $this->toJson(self::ERROR, [], '输入的口号存在中文 `，` ！  请转换成英文`,`后重试,逗号出现在' . $check_title . '附近');
        }
        $check_area = strstr($input['area'], '，');
        if ($check_area) {
            return $this->toJson(self::ERROR, [], '输入的区服中存在中文 `，` ！  请转换成英文`,`后重试,逗号出现在' . $check_area . '附近');
        }
        $check_level = strstr($input['area'], '，');
        if ($check_level) {
            return $this->toJson(self::ERROR, [], '输入的段位中存在中文 `，` ！  请转换成英文`,`后重试,逗号出现在' . $check_level . '附近');
        }
        $res = curl_request(getKkaudioApiUrl() . '/inner/room/type/upsert', $input, 'json', 'POST');
        if ($res['code'] == 0) {
            return $this->toJson(self::SUCCESS);
        }
        return $this->toJson(self::ERROR);

    }

    //CBD房间增加违规记录
    public function violationRecord(Request $request, CbdViolationRecord $cbdViolationRecord)
    {
        $validator = Validator::make($request->all(), [
            'wg_time' => 'required',
            'room_id' => 'required',
            'content' => 'required',
        ], [
            'wg_time.required' => '违规时间必传',
            'room_id.required' => '房间ID必传',
            'content.required' => '违规记录必传'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        $data = $request->input();
        return $this->toJson(self::SUCCESS, $cbdViolationRecord->create($data));
    }

    //获取CBD房间违规记录
    public function getViolationRecord(Request $request, CbdViolationRecord $cbdViolationRecord, $id)
    {
        $data = $request->input();
        return $this->toJson(self::SUCCESS, $cbdViolationRecord->getList($id, $data));
    }

    //编辑CBD房间违规记录
    public function editViolationRecord(Request $request, CbdViolationRecord $cbdViolationRecord)
    {
        $validator = Validator::make($request->all(), [
            'wg_time' => 'required',
            'room_id' => 'required',
            'content' => 'required',
            'id' => 'required',
        ], [
            'wg_time.required' => '违规时间必传',
            'room_id.required' => '房间ID必传',
            'content.required' => '违规记录必传',
            'id.required' => '主键ID必传'
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }

        $data = $request->input();
        return $this->toJson(self::SUCCESS, $cbdViolationRecord->edit($data));
    }

    //删除CBD房间违规记录
    public function deleteViolationRecord(Request $request, CbdViolationRecord $cbdViolationRecord, $id)
    {
        if (!$id) {
            return $this->toJson(self::PARAM_ERROR, [], '主键ID必传');
        }

        return $this->toJson(self::SUCCESS, $cbdViolationRecord->del($id));
    }

    /**
     * 获取开厅时长
     */
    public function getOnlineTime(Request $request, Room $room, $room_id)
    {
        if (empty($room_id)) {
            return $this->toJson(self::PARAM_ERROR, []);
        }

        return $this->toJson(self::SUCCESS, $room->getOnlineTime($request, $room_id));
    }

    /**
     * 连续3天小于8小时名单
     */
    public function getLessRoomOpenTime()
    {
        return $this->toJson(self::SUCCESS, $this->model->getLess8RoomOpenTime());
    }

    /**设置cbd房间车队权限
     * @param Request $request
     * @param Room $room
     * @return \Illuminate\Http\JsonResponse
     */
    public function setCarStatus(Request $request, Room $room)
    {
        $input = $request->all();
        return $this->toJson(self::SUCCESS, $room->setCarStatus($input['room_id'], $input['fleet_king'], $input['fleet_peace'], $input['fleet_mult']));
    }

    public function getLabelById(Request $request, RoomRecommendLabel $roomRecommendLabel)
    {
        $input = $request->all();
        if (empty($input['room_id'])) {
            return $this->toJson(self::PARAM_ERROR);
        }
        $data = $roomRecommendLabel->getRoomLabelById($input['room_id']);
        return $this->toJson(self::SUCCESS, $data);
    }

    public function insertOrUpdateLabel(Request $request, RoomRecommendLabel $roomRecommendLabel)
    {
        $validator = Validator::make($request->all(), [
            'room_id' => 'bail|required|exists:api.room',
            // 'label_id' => 'required',
            // 'starttime' => 'required',
            // 'endtime' => 'required',
            'special_recommend_resource_url' => 'nullable',
            'special_recommend_start_time' => 'nullable',
            'special_recommend_end_time' => 'nullable',
        ], [
            'room_id.required' => '房间不可为空',
            'room_id.exists' => '该房间不存在',
            'label_id.required' => '标签不能为空',
            'starttime.required' => '开始时间不能为空',
            'endtime.required' => '结束时间不能为空',
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }
        $params = $request->only(['room_id', 'label_id', 'starttime', 'endtime',
            'special_recommend_resource_url', 'special_recommend_start_time', 'special_recommend_end_time']);
        $params['label_id'] = $params['label_id'] ?? 0;
        $params['starttime'] = $params['starttime'] ?? date('Y-m-d H:i:s');
        $params['endtime'] = $params['endtime'] ?? date('Y-m-d H:i:s');

        $res = $roomRecommendLabel->insertOrUpdateLabel( $params );
        if ($res['code'] !== 0) {
            return $this->toJson(self::ERROR, $res);
        }
        return $this->toJson(self::SUCCESS, $res);
    }

    public function delNotRecommendLabel($id, RoomRecommendLabel $roomRecommendLabel)
    {
        return $this->toJson(self::SUCCESS, $roomRecommendLabel->delNotRecommendLabel($id));
    }

    //获取房间魅力榜查询
    public function getRoomShotoff(Request $request, RoomShotoff $roomShotoff, $room_id)
    {
        return $this->toJson(self::SUCCESS, $roomShotoff->getList($request, $room_id));
    }

    //获取房间动态封面
    public function getRoomDynamic(Request $request, RoomDynamic $dynamic)
    {
        return $this->toJson(self::SUCCESS, $dynamic->getList($request));
    }

    //获取设置房间封面
    public function setRoomsBg(Request $request, RoomDynamic $dynamic)
    {
        $dynamic_id = $request->input('dynamic_id');
        $end_time = $request->input('end_time');
        $room_id = $request->input('room_id');
        if (strtotime($end_time) < time()) {
            return $this->toJson(self::ERROR, [], '当前已结束');
        }
        $res = curl_request(config('kkaudio.kkaudio_api') . '/inner/room/background/dynamic', [
            'room_id' => $room_id,
            'end_time' => $end_time,
            'dynamic_id' => $dynamic_id
        ], 'json', 'POST');
        if ($res['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::NUMBER, '设置动态封面', $room_id);
            return $this->toJson(self::SUCCESS);
        }
        return $this->toJson(self::ERROR, [], $res['msg']);
    }

    public function getDynamiclog(Request $request, RoomDynamicLog $RoomDynamicLog)
    {
        return $this->toJson(self::SUCCESS, $RoomDynamicLog->getlist($request));
    }

    public function setDynamic(Request $request, RoomDynamic $RoomDynamic)
    {
        $validator = Validator::make($request->all(), [
            'img' => 'bail|required|string',
            'url' => 'bail|required|string',
            'name' => 'bail|required|string',
        ], [
            'img.required' => '参数错误',
            'img.string' => '参数错误',
            'url.required' => '参数错误',
            'url.string' => '参数错误',
            'name.required' => '参数错误',
            'name.string' => '参数错误',
        ]);
        if ($validator->fails()) {
            return $this->toJson(self::PARAM_ERROR, [], $validator->errors()->all()[0]);
        }
        $data = $request->only(['img', 'url', 'name']);
        $id = $request->input('id') ?? 0;
        if ($id) {
            $data['id'] = $id;
        }
        $res = $RoomDynamic->setDynamic($data);
        if ($res['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::NUMBER, '设置动态封面资源', $id);
            return $this->toJson(self::SUCCESS);
        }
        return $this->toJson(self::ERROR, [], $res['msg']);
    }

    public function delDynamic(Request $request, RoomDynamic $RoomDynamic)
    {
        $id = $request->input('id') ?? 0;
        if (!$id) {
            return $this->toJson(self::PARAM_ERROR);
        }
        $res = $RoomDynamic->delDynamic($request->only(['id']));
        if ($res['code'] == 0) {
            OperationLogs::createData($request, OperationLogs::NUMBER, '删除动态封面资源', $id);
            return $this->toJson(self::SUCCESS);
        }
        return $this->toJson(self::ERROR, [], $res['msg']);
    }

    /**
     * 读取一个房间的增减积分记录
     */
    public function getRoomScoreLogList(Request $request)
    {
        $roomId = $request->input('room_id', 0);
        $page = $request->input('page', 1);
        $limit = $request->input('limit', 20);
        if (empty($roomId)) {
            return $this->toJson(self::PARAM_ERROR);
        }
        $list = (new RoomScore())->getScoreLogByRoomId($roomId, 1, $page, $limit);
        return $this->toJson(self::SUCCESS, $list);
    }

    /**
     * 读取一个房间的增减积分记录
     */
    public function setRoomReputation(Request $request)
    {
        $roomId = $request->post("room_id", 0); //房间ID
        $score = $request->post("score", 0); //积分
        $type = $request->post("type", 0); //操作类型：1增加;2减少
        $desc = $request->post("desc", ''); //操作描述
        if (empty($roomId) || empty($score) || empty($type) || empty($desc)) {
            return $this->toJson(self::PARAM_ERROR);
        }
        $token = $request->header('x-token') ?? '';
        $users = Users::findByToken($token);
        $adminName = empty($users->name) ? "" : $users->name;
        $result = (new RoomScore())->setRoomReputation($type, $roomId, $score, $desc, $adminName);
        if($result['code'] > 0){
            return $this->toJson(self::ERROR,[],$result['msg']);
        }
        return $this->toJson(self::SUCCESS, []);
    }

    /**
     * 读取所有房间投票话题
     */
    public function getRoomVoteTopic(Request $request)
    {
        $result = (new RoomVote())->getTopics();
        return $this->toJson(self::SUCCESS, $result);
    }

    /**
     * 编辑房间投票话题
     */
    public function editRoomVoteTopic(Request $request)
    {
        $id = $request->post("id", 0);
        $title = $request->post("title", "");
        if (empty($title)) {
            return $this->toJson(self::PARAM_ERROR);
        }
        $result = (new RoomVote())->editTopic($id, $title);
        if($result['code'] > 0){
            return $this->toJson(self::ERROR,[],$result['msg']);
        }
        return $this->toJson(self::SUCCESS, []);
    }

    /**
     * 删除房间投票话题
     */
    public function delRoomVoteTopic(Request $request)
    {
        $id = $request->post("id", 0);
        if (empty($id)) {
            return $this->toJson(self::PARAM_ERROR);
        }
        $result = (new RoomVote())->delTopic($id);
        if($result['code'] > 0){
            return $this->toJson(self::ERROR,[],$result['msg']);
        }
        return $this->toJson(self::SUCCESS, []);
    }

    /**
     * 获取活动期间房间配置特殊封面
     */
    public function getSpecialCoverRoom(Request $request)
    {
        $roomid = $request->get('roomid',''); //房间id
        if (empty($roomid))
        {
            return $this->toJson(self::PARAM_ERROR, [],'房间id不能为空');
        }
        $data = $this->model->getSpecialRoomInfo($roomid);

        return $this->toJson(self::SUCCESS, $data);
    }

    /**
     * 房间特殊封面配置新增
     */
    public function upSpecialCoverRoom(Request $request)
    {
        $param = $request->all();
        if (empty($param['roomid']))
        {
            return $this->toJson(self::PARAM_ERROR, [],'房间id不能为空');
        }
        if (empty($param['imgurl']))
        {
            return $this->toJson(self::PARAM_ERROR, [],'图片地址不能为空');
        }
        if (empty($param['start_time']))
        {
            return $this->toJson(self::PARAM_ERROR, [],'开始时间不能为空');
        }
        if (empty($param['end_time']))
        {
            return $this->toJson(self::PARAM_ERROR, [],'结束时间不能为空');
        }
        //入库操作
        $res = $this->model->insetOrUpdateData($param);
        return $this->toJson(self::SUCCESS, $res);
    }

    /**
     * 删除活动封面配置
     */
    public function delSpecialCoverRoom(Request $request)
    {
        $param = $request->all();
        if (empty($param['roomid']))
        {
            return $this->toJson(self::PARAM_ERROR, [],'房间id不能为空');
        }
        //入库操作
        $res = $this->model->deleteeData($param);
        return $this->toJson(self::SUCCESS, $res);
    }

    //置顶房间列表
    public function topRoomList(Request $request){
        return $this->toJson(self::SUCCESS, $this->model->topRoomList($request));
    }

    //新增置顶房间
    public function topRoomCreate(Request $request){
        $res = $this->model->topRoomCreate($request->all());
        if($res['code'] != self::SUCCESS) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::UNION, '新增置顶房间');
        return $this->toJson(self::SUCCESS);
    }

    //修改置顶房间
    public function topRoomUpdate(Request $request){
        $res = $this->model->topRoomUpdate($request->all());
        if($res['code'] != self::SUCCESS) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::UNION, '修改置顶房间');
        return $this->toJson(self::SUCCESS);
    }

    //删除置顶房间
    public function topRoomDel(Request $request){
        $res = $this->model->topRoomDel($request->all());
        if($res['code'] != self::SUCCESS) {
            return $this->toJson(self::ERROR, [], $res['msg']);
        }
        OperationLogs::createData($request, OperationLogs::UNION, '删除置顶房间');
        return $this->toJson(self::SUCCESS);
    }

    //设置房间分成用户
    public function setRoomFinanceUser(Request $request){
        $res = $this->model->setRoomFinanceUser($request->all(), $this->user);
        if($res['code'] == self::SUCCESS) {
            OperationLogs::createData($request, OperationLogs::ROOM, '设置房间分成用户');
        }
        return $this->toJson($res['code'], $res['data'], $res['msg']);
    }

    //获取房间分成用户
    public function getRoomFinanceUser(Request $request){
	$res = $this->model->getRoomFinanceUser($request);
        return $this->toJson($res['code'], $res['data'], $res['msg']);
    }

    //房间欢迎语列表
    public function listRoomWelcomeWord(Request $request){
        return $this->toJson(self::SUCCESS, $this->model->listRoomWelcomeWord($request));
    }

    //审核房间欢迎语
    public function auditRoomWelcomeWord(Request $request){
        $res = $this->model->auditRoomWelcomeWord($request->all(), $this->user);
        if($res['code'] == self::SUCCESS) {
            OperationLogs::createData($request, OperationLogs::ROOM, '审核房间欢迎语');
        }
        return $this->toJson($res['code'], $res['data'], $res['msg']);
    }

    //一键通过房间欢迎语
    public function auditBatchRoomWelcomeWord(Request $request){
        $res = $this->model->auditBatchRoomWelcomeWord($request->all(), $this->user);
        if($res['code'] == self::SUCCESS) {
            OperationLogs::createData($request, OperationLogs::ROOM, '一键通过房间欢迎语');
        }
        return $this->toJson($res['code'], $res['data'], $res['msg']);
    }

    //是否隐藏房间
    public function hideRoom(Request $request){
        $roomId = $request->post('room_id',0);//房间id
        $hideStatus = $request->post('is_hide',0);//是否隐藏1=是 0=不是
        if(empty($roomId) || !in_array($hideStatus,[0,1])){
            $this->toJson(self::PARAM_ERROR);
        }
        $res = $this->model->hideRoom($roomId, $hideStatus);
        return $this->toJson($res['code'], $res['data'], $res['msg']);
    }

}
